package com.buba.livenuniappservernew.api.recipe.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.buba.livenuniappservernew.api.Enum.DeleteEnum;
import com.buba.livenuniappservernew.api.recipe.entity.Recipe;
import com.buba.livenuniappservernew.api.recipe.mapper.RecipeMapper;
import com.buba.livenuniappservernew.api.recipe.service.RecipeService;
import com.buba.livenuniappservernew.common.CommonResult;
import com.buba.livenuniappservernew.utils.RedisUtil;
import com.github.yulichang.query.MPJQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 食谱表业务逻辑层
 */
@Service
public class IRecipeServiceImpl implements RecipeService {
    @Autowired
    private RecipeMapper recipeMapper;
    @Autowired
    RedisUtil redisUtil;


    void storeInRedis(List<Recipe> list, String redisKey,int time) {
        try {
            redisUtil.lSet(redisKey, list, time);
        } catch (Exception e) {
            // 记录错误日志
            System.err.println("Error storing in Redis: " + e.getMessage());
        }
    }
    /**
     * 全查食谱
     * 如果携带参数 根据参数查询
     * @return
     */
    @Override
    public CommonResult<List<Recipe>> listRecipe(Integer footType) {
        MPJQueryWrapper<Recipe> wrapper = new MPJQueryWrapper<>();
        wrapper.select("t.*,p.file_uuid_name")
                .join("join",true,"image_file p on t.recipe_file_id = p.image_name")
                .eq("t.del_flag", DeleteEnum.UN_DELETE);
        if (footType!= null) {
            wrapper.eq("t.foot_type", footType);
            List<Recipe> list = recipeMapper.selectJoinList(Recipe.class, wrapper);
            String redisKey1 = null;
            String redisKey2 = null;
            if (footType == 0) {
                redisKey1 = "vegetableRecipe1";
                redisKey2 = "vegetableRecipe2";
            } else if (footType == 1) {
                redisKey1 = "meatRecipe1";
                redisKey2 = "meatRecipe2";
            } else if (footType == 2) {
                redisKey1 = "LowInFatRecipe1";
                redisKey2 = "LowInFatRecipe2";
            }
            storeInRedis(list, redisKey1,100000);
            storeInRedis(list, redisKey2,150000);
            return CommonResult.success(list);
        }
        List<Recipe> list = recipeMapper.selectJoinList(Recipe.class, wrapper);
        redisUtil.lSet("listRecipeRecommended1",list,100000);
        redisUtil.lSet("listRecipeRecommended2",list,150000);
        return CommonResult.success(list);
    }

}
